package cn.monkey.family.server.domain.uc.resource;

import cn.monkey.family.data.Result;
import cn.monkey.family.data.Results;
import cn.monkey.family.data.context.RequestContext;
import cn.monkey.family.data.crud.AbstractCrudService;
import cn.monkey.family.data.uc.resource.Resource;
import cn.monkey.family.data.uc.resource.ResourceMapper;
import cn.monkey.family.data.uc.resource.ResourceQueryRequest;
import cn.monkey.family.data.uc.resource.ResourceVo;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

@Service
public class ResourceService extends AbstractCrudService<String, ResourceQueryRequest, Resource, Resource, ResourceVo, ResourceMapper, ResourceRepository> implements IResourceService {

    public ResourceService(ResourceRepository repository, ResourceMapper mapper) {
        super(repository, mapper);
    }

    @Override
    public Result<Collection<ResourceVo>> getMenuTree(RequestContext requestContext,
                                                      ResourceQueryRequest resourceQueryRequest,
                                                      Sort sort,
                                                      Integer maxDeep) {
        List<Resource> resources = this.repository.findAllByQueryRequest(resourceQueryRequest.toMenuTypeQueryRequest(), sort);
        return CollectionUtils.isEmpty(resources) ?
                Results.ok(Collections.emptyList()) :
                Results.ok(this.mapper.toTree(resources, maxDeep));
    }
}
